package com.nari.kmd_dataservice.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanCopier;

import java.lang.reflect.InvocationTargetException;
import java.util.Objects;

/**
 * @ClassName: CopierUtil
 * @Description: 对象拷贝
 * @Author: zhangnaijiang
 * @Date: 2022/01/27 09:29
 * @Version 1.0.0
 */
@Slf4j
public class CopierUtil {

    /**
     * 单个对象属性拷贝
     *
     * @param source 源对象
     * @param clazz  目标对象Class
     * @param <T>    目标对象类型
     * @param <M>    源对象类型
     * @return 目标对象
     */
    public static <T, M> T copyProperties(M source, Class<T> clazz) {
        if (Objects.isNull(source) || Objects.isNull(clazz)) {
            throw new IllegalArgumentException();
        }
        return copyProperties(source, clazz, null);
    }

    /**
     * 单个对象属性拷贝
     *
     * @param source 源对象
     * @param clazz  目标对象Class
     * @param copier copier
     * @param <T>    目标对象类型
     * @param <M>    源对象类型
     * @return 目标对象
     */
    private static <T, M> T copyProperties(M source, Class<T> clazz, BeanCopier copier) {
        if (null == copier) {
            copier = BeanCopier.create(source.getClass(), clazz, false);
        }
        T t = null;
        try {
            t = clazz.getDeclaredConstructor().newInstance();
            copier.copy(source, t, null);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            log.error("对象拷贝异常，【{}】", e.getMessage());
        }
        return t;
    }
}
